var ModalChoseTable = function(options) {
	var self = this;
	/**
	 * 加载配置并复制给全局变量settings
	 */
	var settings = _extend({}, self.defaults, options);
	/**
	 * 给具有对应的class 或者 唯一id的元素绑定事件
	 */
	if(!(settings['id'] != '' && settings['id'] != undefined && settings['id'] != 'undefined')) {
		console.error("id为必填选项");
	}
	if(!(settings['itemNameKey'] != '' && settings['itemNameKey'] != undefined && settings['itemNameKey'] != 'undefined')) {
		console.error("itemNameKey为必填选项");
	}
	if(!(settings['itemIdKey'] != '' && settings['itemIdKey'] != undefined && settings['id'] != 'undefined')) {
		console.error("itemIdKey为必填选项");
	}
	var choseObject = document.getElementById(settings['id']);
	if(!(settings['dataUrl'] != '' && settings['dataUrl'] != undefined && settings['dataUrl'] != 'undefined')) {
		console.error("dataUrl为必填选项");
	}
	//将所有默认值赋到该标签上
	_on(choseObject, "click", self.createModal);
	setAttr(choseObject, settings);

	var parmeterId = $('#' + settings['id']).attr('data-id');
	if(parmeterId != '' && parmeterId != undefined && parmeterId != 'undefined') {
		settings.parmeterId = parmeterId;
		self.setInitValue(settings);
	}
}

ModalChoseTable.prototype = {
	version: "1.0.0",
	defaults: {
		id: '',
		modalSize: "400px", //弹出框大小
		dataUrl: '', //获取列表的url
		dataParameter: {}, //暂时无用
		resultKey: [], //获取最终集合的键（一定要是结果中包含的），for example: 接口返回的结果为{"result":[],"errorDescription":"Success","errorCode":0}，则resultKey即为['result']
		itemNameKey: '', //结果集合中需要取每个对象的name的键
		itemIdKey: '' //结果集合中需要取每个对象的id的键
	},
	createModal: function(event) {
		var id = $(this).attr('id');
		var settings = getSettings(this, ModalChoseTable.prototype.defaults);
		/**
		 * 创建模态框
		 */
		var dialog = bootbox.dialog({
			size: settings['modalSize'],
			title: settings['title'],
			message: ModalChoseTable.prototype.creatSelection(settings),
			onEscape: function() {
				dialog.modal('hide');
			},
			buttons: {
				confirm: {
					label: '确定',
					className: 'btn-success',
					callback: function() {
						var selector = $('select.chosen-select').children('option:selected');
						selector = selector[selector.length - 1];
						$('#' + id).val($(selector).html());
						$('#' + id).attr("data-id", $(selector).attr('data-id'));
						$('#' + id).attr("data-name", $(selector).html());
					}
				}
			}
		});

		$('select.chosen-select').chosen({
			search_contains: true // 从任意位置开始检索
		});
		$('.chosen-container.chosen-container-single').css("width", "500px");
	},
	creatSelection: function(settings) {
		var url = settings['dataUrl'];
		var data = settings['dataParameter'];
		var itemIdKey = settings['itemIdKey'];
		var itemNameKey = settings['itemNameKey'];
		var resultKey = settings['resultKey'];
		var optionHTML = '';
		requestRemoteDataJsonPost(url, JSON.parse(data), function(res) {
			console.log(res)
			resultKey = resultKey.substr(1, resultKey.length - 2).split(",");
			for(var i = 0; i < resultKey.length; i++) {
				var key = resultKey[i].substr(1, resultKey[i].length - 2);
				res = parseResult(res, key);
			}
			for(var i = 0; i < res.length; i++) {
				var item = res[i];
				optionHTML += '  <option data-id="' + item[itemIdKey] + '" value="' + item[itemNameKey] + '">' + item[itemNameKey] + '</option>';
			}
		}, false);
		var html = '<select data-placeholder="使用汉字检索" class="chosen-select form-control" tabindex="2" style="width:100px;">' +
			'  <option value=""></option>' +
			optionHTML +
			'</select>';
		return html;
	},
	setInitValue: function(settings) {
		var parmeterId = settings['parmeterId'];
		var id = settings['id'];
		var url = settings['dataUrl'];
		var itemNameKey = settings['itemNameKey'];
		var resultKey = settings['resultKey'];
		var data = new Object();
		data.id = parmeterId;
		requestRemoteDataJsonPost(url, data, function(res) {
			console.log(url, res);
			for(var i = 0; i < resultKey.length; i++) {
				res = parseResult(res, resultKey[i]);
			}
			$('#' + id).val(res[0][itemNameKey]);
			$('#' + id).attr("data-name", res[0][itemNameKey]);
		}, true);
	}
}

/**
 * 从第三个参数开始，逐个将对象赋值给第二个参数对象，第一个参数对象，最后返回第一个参数对象
 */
function _extend() {
	var args = arguments;
	for(var i = 0; i < args.length; i++) {
		for(var key in args[i]) {
			if(args[i].hasOwnProperty(key)) {
				args[0][key] = args[i][key];
			}
		}
	}
	return args[0];
}

function _on(el, event, fn) {
	if(el instanceof HTMLCollection || el instanceof Array) {
		for(var i = 0; i < el.length; i++) {
			el[i].removeEventListener(event, fn, false);
			el[i].addEventListener(event, fn, false);
		}
	} else if(el instanceof Object) {
		el.removeEventListener(event, fn, false);
		el.addEventListener(event, fn, false);
	} else {
		console.error("el 类型判断异常");
	}
}

function setAttr(el, paramer) {
	if(el instanceof HTMLCollection || el instanceof Array) {
		for(var i = 0; i < el.length; i++) {
			for(var key in paramer) {
				if(paramer.hasOwnProperty(key)) {
					if(typeof paramer[key] == 'object')
						$(el).attr(key, JSON.stringify(paramer[key]));
					else
						$(el).attr(key, paramer[key]);
				}
			}
		}
	} else if(el instanceof Object) {
		for(var key in paramer) {
			if(paramer.hasOwnProperty(key)) {
				if(typeof paramer[key] == 'object')
					$(el).attr(key, JSON.stringify(paramer[key]));
				else
					$(el).attr(key, paramer[key]);
			}
		}
	} else {
		console.error("el 类型异常");
	}
}

function getSettings(el, defaults) {
	var settings = {};
	for(var key in defaults) {
		if(defaults.hasOwnProperty(key))
			settings[key] = $(el).attr(key);
	}
	return settings;
}

function parseResult() {
	var size = arguments.length;
	if(size == 0) {
		return '';
	}
	var result = arguments[0];
	for(var i = 1; i < size; i++) {
		if(result == undefined) {
			return '';
		}
		var argu = arguments[i];
		if(i == size) {
			return argu;
		}
		result = result[argu];
	}
	return result;
}

function requestRemoteDataJsonPost(url, data, callback, async) {
	//console.log("url-->", url);
	//console.log("data-->", data);
	$.ajax({
		url: url,
		type: 'GET',
		async: async,
		cache: false,
		dataType: "json",
		data: data,
		success: callback,
		error: function(data) {
			var status = data.status;
			console.log(url + "获取数据失败!");
		}
	});
}